use actix_web::{HttpResponse, ResponseError};
use deadpool_postgres::CreatePoolError;
use deadpool_postgres::PoolError;
use derive_more::{Display, From};
use std::num::TryFromIntError;
use std::time::SystemTimeError;
use tokio_pg_mapper::Error as PGMError;
use tokio_postgres::error::Error as PGError;

#[derive(Display, From, Debug)]
pub enum MyError {
    NotFound,
    Msg(String),
    PGError(PGError),
    PGMError(PGMError),
    PoolError(PoolError),
    CreatePoolError(CreatePoolError),
    SystemTimeError(SystemTimeError),
    TryFromIntError(TryFromIntError),
    ConfigError(config::ConfigError),
}

impl std::error::Error for MyError {}

impl From<MyError> for std::io::Error {
    fn from(err: MyError) -> Self {
        std::io::Error::new(std::io::ErrorKind::Other, format!("{}", err))
    }
}
impl ResponseError for MyError {
    fn error_response(&self) -> HttpResponse {
        match *self {
            MyError::NotFound => HttpResponse::NotFound().finish(),
            _ => HttpResponse::InternalServerError().body(format!("{:?}", self)),
        }
    }
}
